package com.rzj.book.realm;

import com.rzj.book.en.Emp;
import com.rzj.book.en.Menu;
import com.rzj.book.en.Role;
import com.rzj.book.service.IEmpService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ErpRealm extends AuthorizingRealm{

    @Autowired 
	private IEmpService empService;
    
	/**
	 * 授权
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行了授权的方法...");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//uuid=?怎么来
		Emp emp = (Emp)principals.getPrimaryPrincipal();
		List<Role> roles = emp.getRoleList();
		Set<String> roleStr = new HashSet<>();//所有角色
		Set<String> permStr = new HashSet<>();//所有权限
		//获取当前登陆用户的菜单权限
		List<Menu> menuList = empService.readMenusByEmpuuid(emp.getEmpId()).getMenus();
		
		//加入授权
		for(Role role : roles){
			roleStr.add(role.getName());
			//这里我们使用menuname来做授权里的key值，那么在配置授权访问的url=perms[菜单名称]
			for(Menu menu : role.getMenus()){
				permStr.add(menu.getMenuName());
			}
		}
		info.setStringPermissions(permStr);
		info.setRoles(roleStr);
		return info;
	}

	/**
	 * 认证
	 * @return null:认证失败, AuthenticationInfo实现类，认证成功
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行了认证的方法...");
		//通过令牌得到用户名和密码?
		UsernamePasswordToken upt = (UsernamePasswordToken)token;
		//得到密码
		String pwd = new String(upt.getPassword());
		//调用登录查询
		Emp emp = empService.findByUsernameAndPwd(upt.getUsername(),pwd);

		if(null != emp){
			//构造参数1： 主角=登陆用户
			//参数2：授权码：密码
			//参数3：realm的名称
			((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().setAttribute("loginUser",emp);
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(emp,pwd,getName());
			return info;
		}
		return null;
	}

}
